using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NLog;

namespace DnsService.Utilities
{
    /// <summary>
    /// 上游DNS主域名配置管理器（key=value），文件位于 Conf/upstream_domains.conf
    /// key: 上游DNS IP，value: 主域名（base domain）
    /// </summary>
    public class UpstreamDomainManager
    {
        private readonly string _filePath;
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();

        public UpstreamDomainManager(string? filePath = null)
        {
            _filePath = string.IsNullOrWhiteSpace(filePath) ? Path.Combine("Conf", "upstream_domains.conf") : filePath!;
        }

        public Dictionary<string, string> Load()
        {
            var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            try
            {
                if (!File.Exists(_filePath))
                {
                    return dict;
                }
                var lines = File.ReadAllLines(_filePath);
                foreach (var raw in lines)
                {
                    var line = raw.Trim();
                    if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) continue;
                    var parts = line.Split('=', 2);
                    if (parts.Length != 2) continue;
                    var key = parts[0].Trim();
                    var value = parts[1].Trim();
                    if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(value))
                    {
                        dict[key] = value;
                    }
                }
            }
            catch
            {
                // 读取失败时返回空字典
            }
            return dict;
        }

        public void Save(Dictionary<string, string> map)
        {
            try
            {
                var dir = Path.GetDirectoryName(_filePath);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                var lines = map.Select(kv => $"{kv.Key}={kv.Value}").ToArray();
                File.WriteAllLines(_filePath, lines);
            }
            catch (Exception ex)
            {
                _logger?.Error(ex, $"保存上游主域名配置失败: {ex.Message}");
            }
        }
    }
}